package com.ftg.learn.chapter12.springbootdemo.service;

import com.ftg.learn.chapter12.springbootdemo.entity.TeachersEntity;
import com.ftg.learn.chapter12.springbootdemo.mapper.TeachersMapper;
import com.ftg.learn.chapter12.springbootdemo.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 布衣
 */
@Service
public class TeacherService {

    @Autowired
    TeachersMapper teachersMapper;

    public List<TeachersEntity> list() {
        return teachersMapper.list();
    }

    public R<String> save(TeachersEntity t) {

        List<TeachersEntity> list = teachersMapper.findOneByName(t.getTeacherName());
        if (list.size() > 0) {
            return R.failure("当前数据已存在！！！");
        }

        int num = teachersMapper.save(t);
        return num > 0 ? R.success() : R.failure("添加失败");

    }

    @Transactional(rollbackFor = SQLException.class)
    public R<String> delById(Integer id) {
        // 是否已经删除了
        if (true) {
            return R.failure("当前数据不存在！！！");
        } else {
            // 考虑课程是滞有当前老师的课 【不能删除，先课程tacherId null】

            // 班级表同上操作
            return teachersMapper.delById(id) > 0 ? R.success() : R.failure("删除失败");
        }
    }
}
